<script lang="ts" setup>
import { ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { useFs } from '@fast-crud/fast-crud';

import { BaseEmployeeApi } from '#/api';
import { useMessage } from '#/hooks/web/useMessage';

import { createCrudOptions } from '../data/bind-user-crud';

defineOptions({
  name: '绑定用户',
  inheritAttrs: false,
});

const tenantId = ref<string>();
const { createMessage } = useMessage();
const { crudRef, crudBinding, crudExpose, selectedRowKeys } = useFs({
  createCrudOptions,
});

const [Modal, modalApi] = useVbenModal({
  async onOpenChange(isOpen) {
    const data = modalApi.getData();
    if (isOpen) {
      selectedRowKeys.value = [];

      tenantId.value = data.record.id;
      crudExpose.setSearchFormData({ form: { tenantId: data.record.id } });
      crudExpose.doRefresh();
    }
  },
  async onConfirm() {
    try {
      modalApi.setState({ loading: true, confirmLoading: true });

      const userIdList = selectedRowKeys.value;

      if (userIdList && userIdList.length > 0) {
        const params = {
          tenantId: tenantId.value,
          userIdList,
          isBind: true,
        };
        await BaseEmployeeApi.bindUser(params);
        createMessage.success('绑定成功');
        modalApi.close();
      } else {
        createMessage.warning('请选择用户');
      }
    } finally {
      modalApi.setState({ loading: false, confirmLoading: false });
    }
  },
});

defineExpose(modalApi);
</script>

<template>
  <Modal
    title="将尚未成为该企业的用户，绑定为此企业的企业管理员"
    class="h-[80%] w-[80%]"
  >
    <FsCrud ref="crudRef" v-bind="crudBinding" />
  </Modal>
</template>
